package com.sdx.console.plan.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.enrollItem.entity.EnrollItem;
import com.sdx.console.enrolledData.entity.TDEnrolledData;
import com.sdx.console.enrolledData.service.TDEnrolledDataService;
import com.sdx.console.plan.entity.TDPlanningData;
import com.sdx.console.plan.service.TDPlanningDataService;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * 招生计划 接口
 */
@RequestMapping("/plandata/tDPlanningData")
@Controller
public class TDPlanningDataController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(TDPlanningDataController.class);
    private static final String MODEL = "/plandata/tDPlanningData";

    private static final String MAJORMODEL = "/plandata/major";

    private static final String PLAN_TABLENAME = "sdxdb.t_d_planning_data_";


    @Resource
	private TDPlanningDataService tDPlanningDataService;

    @Resource
    private TDEnrolledDataService tDEnrolledDataService;

    @Resource
    private SQLManager sqlManager;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
        view.addObject("univList",tDPlanningDataService.selectUniv());
        view.addObject("provinceList",tDEnrolledDataService.selectProv(null));
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("plandata.tDPlanningData.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("plandata.tDPlanningData.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer id,Integer provinceId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        String tablename = PLAN_TABLENAME + provinceId;
        TDPlanningData TDPlanningData = tDPlanningDataService.queryPlanDataById(id,tablename);
        view.addObject("tDPlanningData", TDPlanningData);
		setPageParam(view,request);
		try {
			view.addObject("tDPlanningDataJson", JacksonUtils.toJsonString(TDPlanningData,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("plandata.tDPlanningData.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        view.addObject("tDPlanningData", new TDPlanningData());
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("plandata.tDPlanningData.query")
    @ResponseBody
    public JsonResult<PageQuery> list(TDPlanningData condtion)
    {
        PageQuery page = condtion.getPageQuery();
        condtion.setType(0);
        if(condtion.getProvinceId()!=null){
            String tablename = PLAN_TABLENAME+condtion.getProvinceId();
            condtion.setTablename(tablename);
            tDPlanningDataService.queryByCondition(page);
        }
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,TDPlanningData tDPlanningData,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
        tDPlanningData.setTablename(PLAN_TABLENAME+tDPlanningData.getProvinceId());
    	if (isNew) {
//            tDPlanningData.setMajorCount(0);
            tDPlanningData.setType(0);
//            int planDataCount = tDPlanningDataService.selectPlanDataCount(tDPlanningData);
//            if(planDataCount == 0) {
                tDPlanningDataService.insertPlanData(tDPlanningData);
//            }else{
//                result = JsonResult.failMessage("数据已经存在,请去编辑数据");
//            }
		} else {
			tDPlanningDataService.updatePlanData(tDPlanningData);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("plandata.tDPlanningData.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)TDPlanningData tDPlanningData,HttpServletRequest request
		)
    {

        return save(true,tDPlanningData,request
		);
    }

    @PostMapping("/update.json")
    @Function("plandata.tDPlanningData.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  TDPlanningData tDPlanningData,HttpServletRequest request
		) {
		return save(false,tDPlanningData,request
		);
    }



    @GetMapping("/view.json")
    @Function("plandata.tDPlanningData.query")
    @ResponseBody
    public JsonResult<TDPlanningData>queryInfo(Integer id) {
        TDPlanningData tDPlanningData = tDPlanningDataService.queryById( id);
        return  JsonResult.success(tDPlanningData);
    }

    @PostMapping("/delete.json")
    @Function("plandata.tDPlanningData.del")
    @ResponseBody
    public JsonResult delete(String ids,Integer provId) {
		List<String> idList = Utils.strToList(ids,",");
        String tablename = PLAN_TABLENAME+provId;
        List<String> idAllList = new ArrayList<>();
        for (String s : idList) {
            idAllList.add(s);
            TDPlanningData tDPlanningData = tDPlanningDataService.queryPlanDataById(Integer.parseInt(s),tablename);
            Map<String,Object> map = new HashMap<>();
            map.put("provinceId",provId);
            map.put("year",tDPlanningData.getYear());
            map.put("type",tDPlanningData.getMajorTypeId());
            map.put("tablename",tablename);
            map.put("umId",tDPlanningData.getUmId());
            map.put("batchId",tDPlanningData.getBatchId());
            List<TDPlanningData> list  = tDPlanningDataService.selectMajor(map);
            for (TDPlanningData plan : list) {
                idAllList.add(plan.getId().toString());
            }
        }
        tDPlanningDataService.batchDelTDPlanningData(idAllList,tablename);
        return JsonResult.success();
    }

    @RequestMapping("/getProvinceList.json")
    @ResponseBody
    public List<TDPlanningData>  getProvinceList() {
       return tDPlanningDataService.selectProvince();
    }

    @RequestMapping("/getBaseUniv.json")
    @ResponseBody
    public List<TDPlanningData>  getBaseUniv(Integer batchId,Integer year,Integer type,Integer provinceId) {
        List<TDPlanningData> list = new ArrayList<>();
        if(provinceId!=null){
            Map<String,Object> map = new HashMap<>();
            if(year==2018&&provinceId==1&&batchId==2){
                map.put("batchId","2,3");
            }else {
                map.put("batchId", batchId);
            }
            map.put("year",year);
            map.put("type",type);
            map.put("tablename",PLAN_TABLENAME+provinceId);
            list = tDPlanningDataService.selectBaseUniv(map);
        }

        return list;
    }

    @RequestMapping("/getBatch.json")
    @ResponseBody
    public List<TDPlanningData>  getBatch(Integer id,Integer year,Integer type) {
        Map<String,Object> map = new HashMap<>();
        map.put("id",id);
        map.put("year",year);
        map.put("type",type);
        return tDPlanningDataService.selectBatch(map);
    }


    @GetMapping("/plan.do")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView(MODEL+"/plan.html");
        return view;
    }

     @RequestMapping("/getMajor.json")
     @ResponseBody
     public JsonResult getMajor(Integer year,Integer type,Integer provinceId,Integer umId,Integer batchId) {
         Map<String,Object> map = new HashMap<>();
         map.put("provinceId",provinceId);
         map.put("year",year);
         map.put("type",type);
         map.put("tablename",PLAN_TABLENAME+provinceId);
         map.put("umId",umId);
         if(year==2018&&provinceId==1&&batchId==2){
             map.put("batchId","2,3");
         }else {
             map.put("batchId", batchId);
         }
         List<TDPlanningData> list = new ArrayList<>();
         list = tDPlanningDataService.selectMajor(map);
         JSONObject json = new JSONObject();
         json.put("major",list);
         json.put("plan",tDPlanningDataService.selectTDPlanningData(map));
         return JsonResult.success(json);
     }


    @PostMapping("/addPlanData.json")
    @ResponseBody
    public JsonResult addPlanData(TDPlanningData tDPlanningData,String marjors){
        JsonResult result = JsonResult.success();
        JSONArray array = JSONArray.parseArray(marjors);
        tDPlanningData.setType(0);
        String tablename = PLAN_TABLENAME + tDPlanningData.getProvinceId();
        tDPlanningData.setTablename(tablename);
        //判断是否存在
        int planDataCount = tDPlanningDataService.selectPlanDataCount(tDPlanningData);
        if(planDataCount == 0){
            tDPlanningDataService.insertPlanData(tDPlanningData);
            for (Object object : array) {
                TDPlanningData plan = tDPlanningData;
                plan.setType(1);
                JSONObject  json = (JSONObject)object;
                String majorName = json.getString("majorName").replaceAll("（","(").replaceAll("）",")");
                String majorNameStr = majorName.split("\\(")[0];
                int isMajorClass = 0;
                //判断是否是二级类
                if(majorNameStr.substring(majorNameStr.length()-1, majorNameStr.length()).equals("类")){
                    isMajorClass = 1;
                }

                // 判断是本科还是专科
                String batchName = tDPlanningData.getBatchName();
                int hasRegular = 2;
                if(batchName.contains("专")&&!batchName.contains("提前")){
                    hasRegular = 0;
                }else if(batchName.contains("本")&&!batchName.contains("提前")){
                    hasRegular = 1;
                }

                // 查询专业ID
                Integer majorId = null;
                if(hasRegular<2){
                    majorId = tDPlanningDataService.selectMajorId(majorNameStr, hasRegular);
                }

                plan.setMajorId(majorId);
                plan.setMajorCode(json.getString("majorCode"));
                plan.setMajorName(majorName);
                plan.setMajorEvaluation(json.getString("majorEvaluation"));
                plan.setRemark(json.getString("remark"));
                plan.setCost(json.getString("cost"));
                plan.setSchoolyear(json.getString("schoolyear"));
                plan.setIsMajorClass(isMajorClass);
                plan.setPlan(json.getInteger("plan"));
                plan.setMajorCount(null);
                tDPlanningDataService.insertPlanData(plan);
            }
        }else{
            result = JsonResult.failMessage("数据已经存在,请去编辑数据");
        }
        return result;
    }

    /********************** 专业 start***************************/
    /**
     * 初始化页面需要的列表数据，
     *
     */
    private void setMajorPageParam(ModelAndView view,HttpServletRequest request,Integer provinceId,Integer pId) {
        view.addObject("pId", pId);
        view.addObject("provinceId", provinceId);
        String tablename = PLAN_TABLENAME + provinceId;
        TDPlanningData tDPlanningData = tDPlanningDataService.queryPlanDataById(pId,tablename);
        view.addObject("plandata", tDPlanningData);
        Map<String,Object> map = new HashMap<>();
        map.put("provinceId",provinceId);
        map.put("year",tDPlanningData.getYear());
        map.put("type",tDPlanningData.getMajorTypeId());
        map.put("tablename",tablename);
        map.put("umId",tDPlanningData.getUmId());
        map.put("batchId",tDPlanningData.getBatchId());
        List<TDPlanningData> list  = tDPlanningDataService.selectMajor(map);
        int majorCount = 0;
        for (TDPlanningData plan : list) {
            majorCount += plan.getPlan();
        }
        view.addObject("remainCount", tDPlanningData.getPlan()-majorCount<0?0:tDPlanningData.getPlan()-majorCount);

    }

    /* 页面 */

    @GetMapping("/majorIndex.do")
    @Function("plandata.tDPlanningData.query")
    @ResponseBody
    public ModelAndView majorIndex(HttpServletRequest request,Integer id,Integer provinceId) {
        ModelAndView view = new ModelAndView(MAJORMODEL+"/index.html") ;
        String tablename = PLAN_TABLENAME + provinceId;
        TDPlanningData TDPlanningData =   tDPlanningDataService.queryPlanDataById(id,tablename);
        view.addObject("plan",TDPlanningData);
//        setMajorPageParam(view,request);
        return view;
    }

    @PostMapping("/majorList.json")
    @Function("plandata.tDPlanningData.query")
    @ResponseBody
    public JsonResult<PageQuery> majorList(TDPlanningData condtion){
        String tablename = PLAN_TABLENAME + condtion.getProvinceId();
        TDPlanningData data = tDPlanningDataService.queryPlanDataById(condtion.getId(),tablename);
        data.setId(null);
        data.setType(1);
        data.setTablename(tablename);
        data.setMajorName(condtion.getMajorName());
        data.setCheckFlag(null);
        PageQuery page = data.getPageQuery();
        tDPlanningDataService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @GetMapping("/majorEdit.do")
    @Function("plandata.tDPlanningData.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer id,Integer provinceId,Integer pId) {
        ModelAndView view = new ModelAndView(MAJORMODEL+"/add.html");
        String tablename = PLAN_TABLENAME + provinceId;
        TDPlanningData TDPlanningData = tDPlanningDataService.queryPlanDataById(id,tablename);
        view.addObject("tDPlanningData", TDPlanningData);

        setMajorPageParam(view,request,provinceId,pId);
        try {
            view.addObject("tDPlanningDataJson", JacksonUtils.toJsonString(TDPlanningData,JacksonUtils.DF1));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return view;
    }

    @GetMapping("/majorAdd.do")
    @Function("plandata.tDPlanningData.add")
    @ResponseBody
    public ModelAndView majoAadd(HttpServletRequest request,Integer provinceId,Integer pId) {
        ModelAndView view = new ModelAndView(MAJORMODEL+"/add.html");
        view.addObject("tDPlanningData", new TDPlanningData());
        setMajorPageParam(view,request,provinceId,pId);
        return view;
    }


    @PostMapping("/majoradd.json")
    @Function("plandata.tDPlanningData.add")
    @ResponseBody
    public JsonResult majoradd(@Validated(ValidateConfig.ADD.class)TDPlanningData tDPlanningData,HttpServletRequest request,Integer pId)
    {
        return majorSave(true,tDPlanningData,request,pId);
    }
    @PostMapping("/majorupdate.json")
    @Function("plandata.tDPlanningData.edit")
    @ResponseBody
    public JsonResult<String> majorupdate(@Validated(ValidateConfig.UPDATE.class)  TDPlanningData tDPlanningData,HttpServletRequest request,Integer pId
    ) {
        return majorSave(false,tDPlanningData,request,pId);
    }
    private JsonResult majorSave(boolean isNew, TDPlanningData tDPlanningData, HttpServletRequest request, Integer pId) {
        JsonResult result = JsonResult.success();
        String tablename = PLAN_TABLENAME + tDPlanningData.getProvinceId();
        TDPlanningData plan = tDPlanningDataService.queryPlanDataById(pId, tablename);
        tDPlanningData.setTablename(tablename);

        /********************** 匹配专业 START***************************/
//        String majorName = tDPlanningData.getMajorName().replaceAll("（","(").replaceAll("）",")");
//        String majorNameStr = majorName.split("\\(")[0];
//        int isMajorClass = 0;
//        //判断是否是二级类
//        if(majorNameStr.substring(majorNameStr.length()-1, majorNameStr.length()).equals("类")){
//            isMajorClass = 1;
//        }
//        // 判断是本科还是专科
//        String batchName = plan.getBatchName();
//        int hasRegular = 2;
//        if(batchName!=null&&batchName.contains("专")&&!batchName.contains("提前")){
//            hasRegular = 0;
//        }else if(batchName!=null&&batchName.contains("本")&&!batchName.contains("提前")){
//            hasRegular = 1;
//        }
//        // 查询专业ID
//        Integer majorId = null;
//        if(hasRegular<2){
//            majorId = tDPlanningDataService.selectMajorId(majorNameStr, hasRegular);
//        }
//        tDPlanningData.setMajorId(majorId);
//        tDPlanningData.setIsMajorClass(isMajorClass);
//        tDPlanningData.setMajorName(majorName);

        /********************** 匹配专业 END***************************/

        if(isNew) {
            tDPlanningData.setYear(plan.getYear());
            tDPlanningData.setMajorTypeId(plan.getMajorTypeId());
            tDPlanningData.setBatchId(plan.getBatchId());
            tDPlanningData.setType(1);
            tDPlanningData.setUmId(plan.getUmId());
            tDPlanningData.setUnivId(plan.getUnivId());
            tDPlanningData.setUnivCode(plan.getUnivCode());
            tDPlanningData.setUnivName(plan.getUnivName());
            tDPlanningData.setUnivEvaluation(plan.getUnivEvaluation());
            tDPlanningDataService.insertPlanData(tDPlanningData);
            //更新专业数
            plan.setTablename(tablename);
            if(plan.getMajorCount()!=null){
                plan.setMajorCount(plan.getMajorCount()+1);
            }else{
                plan.setMajorCount(1);
            }
            tDPlanningDataService.updatePlanData(plan);
        }else{
            tDPlanningDataService.updatePlanData(tDPlanningData);
        }
        return  result;

    }

    /**
     * 删除专业
     * @param ids
     * @param provId
     * @param pId
     * @return
     */
    @PostMapping("/majordelete.json")
    @Function("plandata.tDPlanningData.del")
    @ResponseBody
    public JsonResult majordelete(String ids,Integer provId,Integer pId) {
        List<String> idList = Utils.strToList(ids,",");
        String tablename = PLAN_TABLENAME+provId;
        tDPlanningDataService.batchDelTDPlanningData(idList,tablename);

//        //更新学校的专业数  校验状态
//        TDPlanningData tDPlanningData = tDPlanningDataService.queryPlanDataById(pId,tablename);
//        tDPlanningData.setMajorCount(tDPlanningData.getMajorCount()-idList.size());
//        tDPlanningData.setCheckFlag(0);
//        tDPlanningDataService.updatePlanData(tDPlanningData);

        return JsonResult.success();
    }

    @PostMapping("/check.json")
    @Function("plandata.tDPlanningData.check")
    @ResponseBody
    public JsonResult check(String ids,Integer provinceId,HttpServletRequest request) {
        List<String> idList = Utils.strToList(ids,",");
        String tablename = PLAN_TABLENAME+provinceId;
        CoreUser user = getLoginUser(request);

        for (String id : idList) {
            TDPlanningData data = new TDPlanningData();
            data.setTablename(tablename);
            data.setId(Integer.parseInt(id));
            data.setCheckFlag(1);
            data.setChecker(user.getName());
            data.setCheckeTime(new Date());
            tDPlanningDataService.updatePlanData(data);
//            TDPlanningData tDPlanningData = tDPlanningDataService.queryPlanDataById(Integer.parseInt(id),tablename);
//            Map<String,Object> map = new HashMap<>();
//            map.put("provinceId",tDPlanningData.getProvinceId());
//            map.put("year",tDPlanningData.getYear());
//            map.put("type",tDPlanningData.getMajorTypeId());
//            map.put("tablename",tablename);
//            map.put("umId",tDPlanningData.getUmId());
//            map.put("batchId",tDPlanningData.getBatchId());
//            List<TDPlanningData> list  = tDPlanningDataService.selectMajor(map);
//            int planCount = 0;
//            for (TDPlanningData plan : list) {
//                planCount += plan.getPlan();
//            }
//            if(planCount==tDPlanningData.getPlan()){
//                successCount ++ ;
//                TDPlanningData data = new TDPlanningData();
//                data.setTablename(tablename);
//                data.setId(Integer.parseInt(id));
//                data.setCheckFlag(1);
//                data.setMajorCount(list.size());
//                tDPlanningDataService.updatePlanData(data);
//            }else {
//                failCount++;
//            }
        }
//         String msg ="成功:<font color='green'>"+ successCount+"</font>条,失败:<font color='red'>"+failCount+"</font>条！";

        return JsonResult.success();
    }

    @PostMapping("/save.json")
    @ResponseBody
    public JsonResult saveData(TDPlanningData planningData, HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
        System.out.println(PLAN_TABLENAME+planningData.getProvinceId());
        planningData.setChecker(user.getName());
        planningData.setTablename(PLAN_TABLENAME+planningData.getProvinceId());
        tDPlanningDataService.updatePlanData(planningData);
        return JsonResult.success();
    }
}
